package com.example.campuscardmanagementsys;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.*;
import java.util.Map;
@RestController
@CrossOrigin(origins = "http://127.0.0.1:5500", allowCredentials = "true")
@RequestMapping("/api/posts")
public class PostViewController {

    // 获取浏览记录数
    @GetMapping("/{postId}/views")
    public ResponseEntity<?> getViewCount(@PathVariable int postId) {
        String sql = "SELECT COUNT(*) AS view_count FROM PostViews WHERE PostID = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                int count = rs.getInt("view_count");
                return ResponseEntity.ok("浏览次数：" + count);
            } else {
                return ResponseEntity.status(404).body("未找到博客");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("服务器错误");
        }
    }

    // 手动记录一次浏览
    @PostMapping("/{postId}/views")
    public ResponseEntity<?> addView(@PathVariable int postId, @RequestBody(required = false) Map<String, Object> request) {
        Integer userId = null;
        if (request != null && request.containsKey("userId")) {
            userId = (Integer) request.get("userId"); // 可选字段
        }

        String sql = "INSERT INTO PostViews (PostID, UserID) VALUES (?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            if (userId != null) {
                stmt.setInt(2, userId);
            } else {
                stmt.setNull(2, Types.INTEGER);
            }

            int rowsInserted = stmt.executeUpdate();
            if (rowsInserted > 0) {
                return ResponseEntity.ok("记录浏览成功");
            } else {
                return ResponseEntity.status(500).body("插入失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("服务器错误");
        }
    }

    // 数据库连接方法
    private Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/BlogSystem?useSSL=false&serverTimezone=UTC";
        String user = "root";
        String password = "111111";
        return DriverManager.getConnection(url, user, password);
    }
}
